package cn.easyplatform.studio.web.editors.workbench;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.entity.GetEntityListCmd;
import cn.easyplatform.studio.cmd.entity.PagingCmd;
import cn.easyplatform.studio.cmd.entity.QueryCmd;
import cn.easyplatform.studio.cmd.exportAll.GetDicDetailCmd;
import cn.easyplatform.studio.cmd.exportAll.SaveDicDetailCmd;
import cn.easyplatform.studio.cmd.link.GetLinkCmd;
import cn.easyplatform.studio.cmd.module.*;
import cn.easyplatform.studio.cmd.taskLink.PagingTaskLinkCmd;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.ExportExcel;
import cn.easyplatform.studio.utils.PropertiesUtil;
import cn.easyplatform.studio.utils.StringUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.*;
import cn.easyplatform.studio.web.editors.AbstractPanelEditor;
import cn.easyplatform.studio.web.editors.ComponentCallback;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import org.zkoss.poi.hssf.usermodel.HSSFWorkbook;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.*;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.*;
import org.zkoss.zul.event.PagingEvent;
import org.zkoss.zul.event.ZulEvents;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


public class ModuleEditor extends AbstractPanelEditor {
    private enum EditStatus {
        EDIT_CREATE, EDIT_CREATE_CHANGE, EDIT_SELECT, EDIT_SELECT_CHANGE
    }

    private enum ModuleEntityType {
        ModuleEntityNormal, ModuleEntityRoot
    }

    BASE64Encoder encoder = new BASE64Encoder();//编码

    BASE64Decoder decoder = new BASE64Decoder();//解码

    private Toolbarbutton createButton;
    private Toolbarbutton deleteButton;
    private Toolbarbutton saveButton;
    private Toolbarbutton importButton;
    private Toolbarbutton backUpButton;
    private Bandbox searchBandbox;
    private Listbox listbox;
    private Listbox sourcesListbox;
    private Listbox targetsListbox;
    private Textbox idTextbox;
    private Textbox nameTextbox;
    private Decimalbox priceDecimalbox;
    private Textbox despTextbox;
    private Bandbox searchEntityBandbox;
    private Div iconDiv;
    private Image iconImage;
    private Paging showPaging;
    private Radiogroup typeGroup;
    private Textbox addParentTextbox;
    private Combobox parentCombobox;

    private EditStatus editStatus = EditStatus.EDIT_CREATE;
    private ModuleEntityType entityType = ModuleEntityType.ModuleEntityNormal;
    private ModuleVo selectedModule = new ModuleVo();
    private List<EntityVo> selectedEntityVos = new ArrayList<>();
    private List<DicDetailVo> allParent;
    private org.zkoss.image.Image img;
    public ModuleEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
    }

    @Override
    protected void dispatch(Event evt) {
        //创建
        if (evt.getTarget().equals(createButton)) {
            if (editStatus == EditStatus.EDIT_SELECT_CHANGE || editStatus == EditStatus.EDIT_CREATE_CHANGE)
                WebUtils.showConfirm(Labels.getLabel("button.save"), new EventListener<Event>() {
                    @Override
                    public void onEvent(Event event) throws Exception {
                        if (event.getName().equals(Events.ON_OK))
                            Events.postEvent(new Event(Events.ON_CLICK, saveButton));
                        else {
                            editStatus = EditStatus.EDIT_CREATE;
                            showHeaderBtns();
                            selectedModule = new ModuleVo();
                            showValue();
                        }
                    }
                });
            else {
                editStatus = EditStatus.EDIT_CREATE;
                showHeaderBtns();
                selectedModule = new ModuleVo();
                showValue();
            }
        } else if (evt.getTarget().equals(saveButton)) {
            if (Strings.isBlank(idTextbox.getValue())) {
                idTextbox.setFocus(true);
                throw new WrongValueException(idTextbox, Labels.getLabel(
                        "message.no.empty", new Object[]{Labels.getLabel("entity.id")}));
            } else if (Strings.isBlank(nameTextbox.getValue())) {
                nameTextbox.setFocus(true);
                throw new WrongValueException(nameTextbox, Labels.getLabel(
                        "message.no.empty", new Object[]{Labels.getLabel("entity.name")}));
            } else if (selectedModule.getModuleId() == null) {
                //添加
                setValue();
                boolean saveSuccess = StudioApp.execute(new AddModuleCmd(selectedModule));
                if (saveSuccess) {
                    WebUtils.showSuccess(Labels.getLabel("button.save"));
                    search();
                    editStatus = EditStatus.EDIT_CREATE;
                    showHeaderBtns();
                } else {
                    selectedModule = new ModuleVo();
                    WebUtils.showError(Labels.getLabel("message.error", new String[]{Labels.getLabel("button.save")}));
                    return;
                }
            } else {
                //更新
                setValue();
                Boolean saveSuccess = StudioApp.execute(new UpdateModuleCmd(selectedModule));
                if (saveSuccess) {
                    WebUtils.showSuccess(Labels.getLabel("button.save"));
                    search();
                    editStatus = EditStatus.EDIT_SELECT;
                    showHeaderBtns();
                } else {
                    WebUtils.showError(Labels.getLabel("message.error", new String[]{Labels.getLabel("button.save")}));
                }
            }
        } else if (evt.getTarget().equals(deleteButton)) {
            //删除
            if (selectedModule.getModuleId() == null) {
                WebUtils.showError(Labels.getLabel("editor.select",
                        new String[]{Labels.getLabel("guide.step.element")}));
                return;
            }
            WebUtils.showConfirm(Labels.getLabel("button.delete"), new EventListener<Event>() {
                @Override
                public void onEvent(Event event) throws Exception {
                    if (event.getName().equals(Events.ON_OK)) {
                        Boolean saveSuccess = StudioApp.execute(new DeleteModuleCmd(selectedModule));
                        if (saveSuccess) {
                            WebUtils.showSuccess(Labels.getLabel("button.delete"));
                            getSelectedRow().detach();
                            search();
                            selectedModule = new ModuleVo();
                            showValue();
                            editStatus = EditStatus.EDIT_CREATE;
                            showHeaderBtns();
                        }
                    }
                }
            });
        } else if (evt.getTarget() instanceof Listitem) {
            if (evt.getTarget().getParent().equals(listbox)) {
                //选择
                final Listitem row = (Listitem) evt.getTarget();
                //列表行点击
                if (editStatus == EditStatus.EDIT_SELECT_CHANGE || editStatus == EditStatus.EDIT_CREATE_CHANGE)
                    WebUtils.showConfirm(Labels.getLabel("button.save"), new EventListener<Event>() {
                        @Override
                        public void onEvent(Event event) throws Exception {
                            if (event.getName().equals(Events.ON_OK))
                                Events.postEvent(new Event(Events.ON_CLICK, saveButton));
                            else {
                                selectedModule = row.getValue();
                                editStatus = EditStatus.EDIT_SELECT;
                                showHeaderBtns();
                                showValue();
                            }
                        }
                    });
                else {
                    selectedModule = row.getValue();
                    editStatus = EditStatus.EDIT_SELECT;
                    showHeaderBtns();
                    showValue();
                }
            } else if (evt.getTarget().getParent().equals(sourcesListbox) &&
                    entityType == ModuleEntityType.ModuleEntityRoot) {
                if (evt.getName().equals((Events.ON_DOUBLE_CLICK))) {
                    Listitem ti = (Listitem) evt.getTarget();
                    EntityVo vo= ti.getValue();
                    AbstractView.createRootTaskView(new ComponentCallback(sourcesListbox,
                                    Labels.getLabel("entity.link.detail.title")),
                            vo.getId()).doOverlapped();
                } else if (evt.getName().equals((Events.ON_CLICK))) {
                    Set<Listitem> treeItems = sourcesListbox.getSelectedItems();
                    selectedEntityVos = new ArrayList<>();
                    for (Listitem treeitem : treeItems) {
                        EntityVo vo = treeitem.getValue();
                        selectedEntityVos.add(new EntityVo(vo.getId(), vo.getName(), vo.getDesp(),
                                vo.getType(), vo.getSubType()));
                    }
                }
            }
        } else if (evt.getTarget() instanceof Textbox && evt.getName().equals(Events.ON_CHANGE)) {
            //写入
            setChange();
        } else if (evt.getTarget().getId().equals("module_button_pic")) {
            //设置图片
            setChange();
            UploadEvent event = (UploadEvent) evt;
            org.zkoss.util.media.Media media = event.getMedia();
            if (media instanceof org.zkoss.image.Image) {
                img = (org.zkoss.image.Image) media;
                iconDiv.setVisible(false);
                iconImage.setVisible(true);
                iconImage.setContent(img);
            } else {
                //Messagebox.show("Not an image: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
                WebUtils.showError(Labels.getLabel("file.upload.error"));
            }
            /*List<String> imgPathList = new ArrayList<>();
            if (Strings.isBlank(imagePath) == false) {
                imgPathList = new ArrayList<>(Arrays.asList(selectedModule.getPics().split(",")));
            }
            AbstractView.createModuleImageView(new EditorCallback() {
                @Override
                public Object getValue() {
                    return null;
                }

                @Override
                public void setValue(Object value) {
                    List<String> pathList = (List<String>) value;
                    if (pathList.size() > 0)
                        imagePath = StringUtil.listToString(pathList, ",");
                    else
                        imagePath = "";
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.file.img.imgUpload");
                }

                @Override
                public Page getPage() {
                    return listbox.getPage();
                }

                @Override
                public Editor getEditor() {
                    return ModuleEditor.this;
                }
            }, imgPathList, evt.getTarget()).doOverlapped();*/

        } else if (evt.getTarget().getId().equals("module_image_chooseAllBtn")) {
            select(false);
            setChange();
        } else if (evt.getTarget().getId().equals("module_image_chooseBtn")) {
            select(true);
            setChange();
        } else if (evt.getTarget().getId().equals("module_image_removeBtn")) {
            unselect(true);
            setChange();
        } else if (evt.getTarget().getId().equals("module_image_removeAllBtn")) {
            unselect(false);
            setChange();
        } else if (evt.getTarget() == showPaging) {// 分页
            PagingEvent pe = (PagingEvent) evt;
            int pageNo = pe.getActivePage() + 1;
            if (entityType == ModuleEntityType.ModuleEntityNormal) {
                List<EntityVo> data = StudioApp.execute(showPaging,
                        new PagingCmd(null, "*", null, showPaging.getPageSize(), pageNo));
                createEntityTables(data);
            } else {
                QueryTypeLinkVo result = StudioApp.execute(showPaging,
                        new PagingTaskLinkCmd("*", null, showPaging.getPageSize(), pageNo));
                createEntityTablesWithTaskLink(result.getLinkVoList());
            }
        } else if (evt.getTarget() instanceof Bandbox) {
            if (evt.getTarget().equals(searchBandbox)) {
                //搜索框
                selectedModule = new ModuleVo();
                showValue();
                if (evt instanceof OpenEvent) {
                    OpenEvent event = (OpenEvent) evt;
                    String val = (String) event.getValue();
                    searchBandbox.setValue(val);
                }
                //搜索
                search();
            } else {
                if (evt instanceof OpenEvent) {
                    OpenEvent event = (OpenEvent) evt;
                    String val = (String) event.getValue();
                    searchEntityBandbox.setValue(val);
                }
                //搜索
                searchEntity();
            }
        } else if (evt.getTarget().equals(sourcesListbox)) {
            Set<Listitem> unselectedItems = ((SelectEvent) evt).getUnselectedItems();
            Set<Listitem> selectedItems = ((SelectEvent) evt).getSelectedItems();
            for (Listitem item : selectedItems) {
                EntityVo entityVo = item.getValue();
                if (selectedEntityVos.contains(entityVo) == false)
                    selectedEntityVos.add(entityVo);
            }

            for (Listitem item : unselectedItems) {
                EntityVo entityVo = item.getValue();
                if (selectedEntityVos.contains(entityVo) == true)
                    selectedEntityVos.remove(entityVo);
            }
        } else if (evt.getTarget().equals(importButton)) {
            String[] fields = new String[]{"moduleId", "moduleName", "price", "desp", "pics", "entityIds",
                    "chooseType", "rootEntityIds", "createDate", "updateDate", "createUser", "updateUser"};
            HSSFWorkbook wb = new HSSFWorkbook();

            List<ModuleVo> data = StudioApp.execute(new GetModuleCmd(null));
            List<Object[]> allData = new ArrayList<>();
            for (ModuleVo vo : data) {
                allData.add(new Object[]{vo.getModuleId(), vo.getModuleName(), vo.getPrice(), vo.getDesp(), "",
                vo.getEntityIds(), vo.getChooseType(), vo.getRootEntityIds(), vo.getCreateDate(), vo.getUpdateDate(),
                vo.getCreateUser(), vo.getUpdateUser()});
            }
            String sheetOnecontent[][] = null;
            if (data != null && data.size() != 0) {
                sheetOnecontent = new String[data.size()][allData.get(0).length];
                for (int i = 0; i < data.size(); i++) {
                    Object[] objects = allData.get(i);
                    for (int a = 0; a < objects.length; a++) {
                        sheetOnecontent[i][a] = objects[a] != null ? objects[a] + "" : "";
                    }
                }
            }
            List<Map<String, Object>> excelData = new ArrayList<>();
            Map<String, Object> three = new HashMap<String, Object>();
            three.put("title", fields);
            three.put("values", sheetOnecontent);
            excelData.add(three);
            ExportExcel.getHSSFWorkbook("module", excelData, wb);

            try {
                File tempFile = File.createTempFile("datas", ".xls");
                FileOutputStream os = new FileOutputStream(tempFile);
                wb.write(os);
                os.flush();
                os.close();
                Filedownload.save(tempFile, "application/vnd.ms-excel");
                tempFile.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (evt.getTarget().equals(backUpButton)) {
            new PropertiesUtil().addToolsBackupPath();
            File file = new File(Contexts.getProject().getProperties().get("tools.app.backup.path"));
            if (file.exists() == false) {
                WebUtils.showError(Labels.getLabel("editor.backup.error"));
            } else {
                if (StudioApp.execute(new BackupCmd(file.getPath())) == true)
                    WebUtils.showSuccess(Labels.getLabel("editor.backup.success"));
            }
        } else if (evt.getName().equals(Events.ON_CHECK)) {
            final Integer index = typeGroup.getSelectedIndex();
            boolean isChange = false;
            if (index == 0) {
                if (entityType == ModuleEntityType.ModuleEntityRoot)
                    isChange = true;
                entityType = ModuleEntityType.ModuleEntityNormal;
            } else {
                if (entityType == ModuleEntityType.ModuleEntityNormal)
                    isChange = true;
                entityType = ModuleEntityType.ModuleEntityRoot;
            }

            searchEntityBandbox.setValue(null);
            if (isChange) {
                if (editStatus != EditStatus.EDIT_CREATE) {
                    WebUtils.showConfirm(Labels.getLabel("editor.module.change"), new EventListener<Event>() {
                        @Override
                        public void onEvent(Event event) throws Exception {
                            if (event.getName().equals(Events.ON_OK))
                                createSourceTables();
                            else {
                                if (index == 0) {
                                    typeGroup.setSelectedIndex(1);
                                    entityType = ModuleEntityType.ModuleEntityRoot;
                                } else {
                                    typeGroup.setSelectedIndex(0);
                                    entityType = ModuleEntityType.ModuleEntityNormal;
                                }
                            }
                        }
                    });
                }
            }
        } else if (evt.getTarget().getId().equals("module_button_parentCreate")) {
            if (Strings.isBlank(addParentTextbox.getValue())) {
                addParentTextbox.setFocus(true);
                throw new WrongValueException(addParentTextbox, Labels.getLabel(
                        "message.no.empty", new Object[]{Labels.getLabel("editor.module.parent.placeholder")}));
            } else {
                DicDetailVo detailVo = new DicDetailVo();
                detailVo.setDicCode("9010010018");
                if (allParent == null  || allParent.size() == 0) {
                    detailVo.setDetailNO("1");
                } else {
                    int maxNo = 1;
                    for (DicDetailVo dicDetailVo: allParent) {
                        if (Integer.parseInt(dicDetailVo.getDetailNO()) > maxNo)
                            maxNo = Integer.parseInt(dicDetailVo.getDetailNO());
                    }

                    detailVo.setDetailNO(Integer.toString(maxNo + 1));
                }
                detailVo.setDesc1(addParentTextbox.getValue());
                StudioApp.execute(new SaveDicDetailCmd(detailVo));
                WebUtils.showSuccess(Labels.getLabel("button.add"));
                allParent = StudioApp.execute(new GetDicDetailCmd("9010010018"));
                createParentCombboox(allParent);
            }
        }
    }

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("editor.product.set"), "~./images/module.png",
                "~./include/editor/workbench/module.zul");
        createButton = (Toolbarbutton) is.getFellow("module_toolbarbutton_insert");
        createButton.addEventListener(Events.ON_CLICK, this);
        deleteButton = (Toolbarbutton) is.getFellow("module_toolbarbutton_delete");
        deleteButton.addEventListener(Events.ON_CLICK, this);
        saveButton = (Toolbarbutton) is.getFellow("module_toolbarbutton_save");
        saveButton.addEventListener(Events.ON_CLICK, this);
        importButton = (Toolbarbutton) is.getFellow("module_toolbarbutton_dbImport");
        importButton.addEventListener(Events.ON_CLICK, this);
        backUpButton = (Toolbarbutton) is.getFellow("module_toolbarbutton_backup");
        backUpButton.addEventListener(Events.ON_CLICK, this);
        searchBandbox = (Bandbox) is.getFellow("module_bandbox_search");
        searchBandbox.addEventListener(Events.ON_OK, this);
        searchBandbox.addEventListener(Events.ON_OPEN, this);
        listbox = (Listbox) is.getFellow("module_listbox_list");
        showPaging = (Paging) is.getFellow("module_paging_showPaging");
        sourcesListbox = (Listbox) is.getFellow("module_listbox_sources");
        sourcesListbox.addEventListener(Events.ON_SELECT, this);
        targetsListbox = (Listbox) is.getFellow("module_listbox_targets");
        idTextbox = (Textbox) is.getFellow("module_textbox_id");
        idTextbox.addEventListener(Events.ON_CHANGE, this);
        nameTextbox = (Textbox) is.getFellow("module_textbox_name");
        nameTextbox.addEventListener(Events.ON_CHANGE, this);
        priceDecimalbox = (Decimalbox) is.getFellow("module_decimalbox_price");
        priceDecimalbox.addEventListener(Events.ON_CHANGE, this);
        despTextbox = (Textbox) is.getFellow("module_textbox_desp");
        despTextbox.addEventListener(Events.ON_CHANGE, this);
        searchEntityBandbox = (Bandbox) is.getFellow("module_bandbox_entity_search");
        searchEntityBandbox.addEventListener(Events.ON_OK, this);
        searchEntityBandbox.addEventListener(Events.ON_OPEN, this);
        //iconDiv = (Div) is.getFellow("module_div_iconDiv");
        //iconImage = (Image) is.getFellow("module_image_iconShow");
        addParentTextbox = (Textbox) is.getFellow("module_textbox_parentName");
        parentCombobox = (Combobox) is.getFellow("module_combobox_parent");
        parentCombobox.addEventListener(Events.ON_CHANGE, this);
        typeGroup = (Radiogroup) is.getFellow("module_radiogroup_type");
        typeGroup.setSelectedIndex(0);
        typeGroup.addEventListener(Events.ON_CHECK, this);

        /*Button iconUpdateBtn = (Button) is.getFellow("module_button_pic");
        iconUpdateBtn.addEventListener(Events.ON_UPLOAD, this);*/
        Button createParent = (Button) is.getFellow("module_button_parentCreate");
        createParent.addEventListener(Events.ON_CLICK, this);
        Iterator<Component> imgItr = is.queryAll("image").iterator();
        while (imgItr.hasNext()) {
            imgItr.next().addEventListener(Events.ON_CLICK, this);
        }
        redraw();
    }

    //UI
    private void showHeaderBtns() {
        if (editStatus == EditStatus.EDIT_CREATE) {
            saveButton.setDisabled(true);
            deleteButton.setDisabled(true);
        } else if (editStatus == EditStatus.EDIT_CREATE_CHANGE || editStatus == EditStatus.EDIT_SELECT_CHANGE) {
            saveButton.setDisabled(false);
            deleteButton.setDisabled(true);
        } else if (editStatus == EditStatus.EDIT_SELECT) {
            saveButton.setDisabled(true);
            deleteButton.setDisabled(false);
        }
    }

    private void showEntityPaging(int totalSize) {
        showPaging.setVisible(true);
        showPaging.setTotalSize(totalSize);
        showPaging.addEventListener(ZulEvents.ON_PAGING, this);
    }

    private Listitem getSelectedRow() {
        if (selectedModule == null)
            return null;
        return listbox.getSelectedItem();
    }

    private void createParentCombboox(List<DicDetailVo> detailVos) {
        parentCombobox.getItems().clear();
        for (DicDetailVo detailVo : detailVos) {
            Comboitem ci = new Comboitem(detailVo.getDesc1());
            ci.setValue(detailVo.getDetailNO());
            ci.setParent(parentCombobox);
        }
    }

    private void createModuleTables(List<ModuleVo> moduleVos) {
        listbox.getItems().clear();
        List<Listitem> items = listbox.getItems();
        for (ModuleVo vo : moduleVos) {
            Listitem ti = new Listitem();
            ti.appendChild(new Listcell(vo.getModuleId()));
            ti.appendChild(new Listcell(vo.getModuleName()));
            ti.appendChild(new Listcell(vo.getDesp()));
            ti.appendChild(new Listcell(vo.getEntityIds()));
            ti.appendChild(new Listcell(vo.getPrice()));
            ti.setValue(vo);
            ti.addEventListener(Events.ON_CLICK, this);
            items.add(ti);
        }
    }

    private void select(boolean selectFlag) {
        for (Listitem sel : sourcesListbox.getItems()) {
            if (selectFlag && !sel.isSelected())
                continue;
            if (sel.getValue() != null) {
                boolean exists = false;
                EntityVo s = sel.getValue();
                for (Listitem li : targetsListbox.getItems()) {
                    EntityVo t = li.getValue();
                    if (s.getId().equals(t.getId())) {
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    Listitem li = new Listitem();
                    li.appendChild(new Listcell(s.getId()));
                    li.appendChild(new Listcell(s.getName()));
                    li.appendChild(new Listcell(s.getType()));
                    li.appendChild(new Listcell(s.getDesp()));
                    li.setValue(s);
                    targetsListbox.appendChild(li);
                }
            }
        }
    }

    private void unselect(boolean selectedFlag) {
        if (selectedFlag) {
            if (targetsListbox.getSelectedCount() > 0) {
                List<Listitem> items = new ArrayList<>();
                for (Listitem li : targetsListbox.getSelectedItems())
                    items.add(li);
                for (Listitem li : items)
                    li.detach();
            }
        } else
            targetsListbox.getItems().clear();
    }

    private void redraw() {
        //生成模块列表
        List<ModuleVo> moduleVos = StudioApp.execute(new GetModuleCmd(null));
        createModuleTables(moduleVos);
        createSourceTables();
        allParent = StudioApp.execute(new GetDicDetailCmd("9010010018"));
        createParentCombboox(allParent);
    }

    private void createSourceTables() {
        targetsListbox.getItems().clear();
        selectedEntityVos = new ArrayList<>();
        if (entityType == ModuleEntityType.ModuleEntityNormal) {
            //获取参数
            QueryResultVo result = StudioApp.execute(sourcesListbox,
                    new QueryCmd(showPaging.getPageSize()));
            createEntityTables(result.getEntities());
            showEntityPaging(result.getTotalSize());

        } else {
            QueryTypeLinkVo result = StudioApp.execute(showPaging,
                    new PagingTaskLinkCmd("*", null, showPaging.getPageSize(), 1));
            createEntityTablesWithTaskLink(result.getLinkVoList());
            showEntityPaging(result.getTotalSize());
        }
        showPaging.setActivePage(0);
    }

    private void createTargetsTables(List<EntityVo> data) {
        targetsListbox.getItems().clear();
        for (EntityVo vo : data) {
            Listitem row = new Listitem();
            row.setValue(vo);
            row.appendChild(new Listcell(vo.getId()));
            row.appendChild(new Listcell(vo.getName()));
            row.appendChild(new Listcell(vo.getType()));
            row.appendChild(new Listcell(vo.getDesp()));
            row.setParent(targetsListbox);
        }
    }

    private void createEntityTables(List<EntityVo> data) {
        sourcesListbox.getItems().clear();
        for (EntityVo vo : data) {
            Listitem row = new Listitem();
            row.setValue(vo);
            row.appendChild(new Listcell(vo.getId()));
            row.appendChild(new Listcell(vo.getName()));
            row.appendChild(new Listcell(vo.getType()));
            row.appendChild(new Listcell(vo.getDesp()));
            row.setParent(sourcesListbox);
            if (selectedEntityVos.contains(vo))
                row.setSelected(true);
            else
                row.setSelected(false);
        }
    }

    private void createEntityTablesWithTaskLink(List<TypeLinkVo> list) {
        sourcesListbox.getItems().clear();
        for (TypeLinkVo vo : list) {
            if (LinkVo.ENTITYSTATUS.equals(vo.getStatus()) && vo.ROOTENTITYID.equals(vo.isRoot())) {
                Listitem item = new Listitem();
                item.setValue(new EntityVo(vo.getEntityId(), vo.getEntityName(), vo.getEntityDesp(), vo.getEntityType(), vo.getEntitySubType()));
                item.appendChild(new Listcell(vo.getEntityId()));
                item.appendChild(new Listcell(vo.getEntityName()));
                item.appendChild(new Listcell(vo.getEntityType()));
                item.appendChild(new Listcell(vo.getEntityDesp()));
                item.addEventListener(Events.ON_CLICK, this);

                List<String> selectedEntityId = new ArrayList<>();
                for (EntityVo entityVo : selectedEntityVos) {
                    selectedEntityId.add(entityVo.getId());
                }

                if (selectedEntityId.contains(vo.getEntityId()))
                    item.setSelected(true);
                else
                    item.setSelected(false);
                item.addEventListener(Events.ON_DOUBLE_CLICK, this);
                item.setParent(sourcesListbox);
            }
        }
    }

    private void setChange() {
        if (editStatus == EditStatus.EDIT_CREATE)
            editStatus = EditStatus.EDIT_CREATE_CHANGE;
        else if (editStatus == EditStatus.EDIT_SELECT)
            editStatus = EditStatus.EDIT_SELECT_CHANGE;
        showHeaderBtns();
    }

    //数据
    private void showValue() {
        idTextbox.setValue(selectedModule.getModuleId());
        nameTextbox.setValue(selectedModule.getModuleName());
        priceDecimalbox.setValue(selectedModule.getPrice());
        despTextbox.setValue(selectedModule.getDesp());
        parentCombobox.setValue(selectedModule.getDicDetailID());
        /*img = null;
        if (Strings.isBlank(selectedModule.getPics()) == false) {
            try {
                img = new AImage("logo.png", decoder.decodeBuffer(selectedModule.getPics()));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (img != null && img.getWidth() != 0) {
            iconDiv.setVisible(false);
            iconImage.setVisible(true);
            iconImage.setContent(img);
        } else {
            iconDiv.setVisible(true);
            iconImage.setVisible(false);
        }*/

        selectedEntityVos = new ArrayList<>();
        searchEntityBandbox.setValue(null);
        searchEntity();
        if (Strings.isBlank(selectedModule.getChooseType()))
            selectedModule.setChooseType("N");
        entityType = selectedModule.getChooseType().equals("R") ? ModuleEntityType.ModuleEntityRoot:
                ModuleEntityType.ModuleEntityNormal;
        typeGroup.setSelectedIndex(entityType == ModuleEntityType.ModuleEntityRoot ? 1: 0);
        if (Strings.isBlank(selectedModule.getEntityIds()) == false) {
            List<String> entityIDs;
            if (entityType == ModuleEntityType.ModuleEntityNormal)
                entityIDs = Arrays.asList(selectedModule.getEntityIds().split(","));
            else
                entityIDs = Arrays.asList(selectedModule.getRootEntityIds().split(","));
            List<EntityVo> entityVos = StudioApp.execute(new GetEntityListCmd(entityIDs));
            createTargetsTables(entityVos);
        } else
            targetsListbox.getItems().clear();

    }

    private void setValue() {
        selectedModule.setModuleId(idTextbox.getValue());
        selectedModule.setModuleName(nameTextbox.getValue());
        selectedModule.setPrice(priceDecimalbox.getValue().toString());
        selectedModule.setDesp(despTextbox.getValue());
        selectedModule.setDicDetailID(parentCombobox.getValue());
        if (img == null)
            selectedModule.setPics(null);
        else {
            selectedModule.setPics(encoder.encode(img.getByteData()));
        }

        List<String> idList = new ArrayList<>();
        for (Listitem item : targetsListbox.getItems()) {
            EntityVo entityVo = item.getValue();
            if (entityVo != null && Strings.isBlank(entityVo.getId()) == false) {
                idList.add(entityVo.getId());
            }
        }
        if (entityType == ModuleEntityType.ModuleEntityNormal) {
            selectedModule.setRootEntityIds(null);
            selectedModule.setEntityIds(StringUtil.listToString(idList, ","));
            selectedModule.setChooseType("N");
        } else {
            selectedModule.setRootEntityIds(StringUtil.listToString(idList, ","));
            List<LinkVo> entityLinkList = StudioApp.execute(new GetLinkCmd(idList, true));
            List<String> entityIDList = new ArrayList<>();
            for (LinkVo vo : entityLinkList) {
                entityIDList.add(vo.getEntityId());
            }
            selectedModule.setEntityIds(StringUtil.listToString(entityIDList, ","));
            selectedModule.setChooseType("R");
        }
    }

    private void search() {
        String val = searchBandbox.getValue().trim();
        List<ModuleVo> moduleVos = StudioApp.execute(new GetModuleCmd(val));
        createModuleTables(moduleVos);
    }

    private void searchEntity() {
        //获取参数
        showPaging.setActivePage(0);
        String val = searchEntityBandbox.getValue().trim();
        if (entityType == ModuleEntityType.ModuleEntityNormal) {
            QueryResultVo result = null;
            if (Strings.isBlank(val)) {
                result = StudioApp.execute(sourcesListbox, new QueryCmd(null,
                        showPaging.getPageSize()));
            } else {
                result = StudioApp.execute(sourcesListbox, new QueryCmd(null, "*",
                        val.trim(), showPaging.getPageSize()));
            }
            createEntityTables(result.getEntities());
            showEntityPaging(result.getTotalSize());
        } else {
            QueryTypeLinkVo result = null;
            if (Strings.isBlank(val))
                result = StudioApp.execute(showPaging,
                        new PagingTaskLinkCmd("*", null, showPaging.getPageSize(), 1));
            else
                result = StudioApp.execute(showPaging,
                        new PagingTaskLinkCmd("*", val, showPaging.getPageSize(), 1));

            createEntityTablesWithTaskLink(result.getLinkVoList());
            showEntityPaging(result.getTotalSize());
        }
    }
}
